//==================客户端======================
const dateKit = require( "./util/dateKit");
const dataKit = require( "./util/dataKit");
const util = require( "./util/util")
const clientService = require( "./util/clientService")

/**
 * 登录
 * userNick 用户昵称
 */
exports.login = async (context) => {
    const {userNick} = context.data;
    const {openId,appOwnerOpenId} = context;

    if(!userNick){
        return {code:-1,msg:"userNick不能为空"}
    }
    
    let userInfo = await clientService.getUserByOpenId(context,openId);
    if(!userInfo){
        userInfo = {openId:openId,
                    createTime:dateKit.getCurrentDateTime()};
    }
    
    userInfo.appOwnerOpenId=appOwnerOpenId;
    userInfo.userNick=userNick;
    userInfo.loginTime = dateKit.getCurrentDateTime();
    const result = await dataKit.insertOrUpdate(context,"user_info",userInfo);
    
    return {code:0,msg:"登录成功"};
};

/**
 * 获取商品列表
 */
exports.getProductList = async (context) => {
    let result = await clientService.getProductList(context);
    return {code:0,msg:"获取成功",data:result};
};

/**
 * 会员身份识别
 */
exports.isTaobaoMember = async (context) => {
    let result = await clientService.isTaobaoMember(context,context.mixNick);
    return {code:0,msg:"获取成功",data:result};
};

/**
 * 获取用户当前积分（需要商家授权token）
 */
exports.getAvailablePoint = async (context) => {
    let result = await clientService.getAvailablePoint(context,context.mixNick);
    return {code:0,msg:"获取成功",data:result};
};

/**
 * 发送权益
 */
exports.sendBenefit = async (context) => {
    const {openId,ename} = context.data; 
    const result = await clientService.sendBenefit(context,openId,ename,util.uuid());
    return {code:0,msg:"发奖成功",data:result};
}


/**
 * 获取排名（根据注册时间排名）- 示例
 * 注：使用count查询计算排名，可能有更好的方法，此案例仅供参考
 */
exports.rank = async (context) => {
    const {openId} = context.data; 

    if(!openId){
        return {code:-12,msg:"openId不能为空"};
    }

    //当前用户的信息
    const user_info = await dataKit.findOne(context,"user_info",{openId});
    const createTime = user_info.createTime;

    //获取比当前用户小于等于(排出当前用户当前用户)的数量
    const count = await dataKit.count(context,
                                    "user_info",
                                    {
                                         createTime:{$lte:createTime},
                                         openId:{$ne:openId}
                                    });
    //排名数量
    const rank = count+1;
    return {code:0,msg:"获取成功",data:rank};
};

/**
 * 时间比较(案例)
 */
exports.compare  = async (context) => {

    return {
        "2020-12-12 00:00:00 对比 2020-11-11 00:00:00 = 1" : dateKit.compare("2020-12-12 00:00:00","2020-11-11 00:00:00"),
        "2020-12-12 12:00:00 对比 2020-12-12 12:11:00 = -1" : dateKit.compare("2020-12-12 12:00:00","2020-12-12 12:11:00"),
        "2020-12-2 00:00:00 对比 2020-12-01 00:00:00 = 1" : dateKit.compare("2020-12-2 00:00:00","2020-12-01 00:00:00"),
    };
}